package org.fedex.rg.servises.impl;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.fedex.rg.model.Song;
import org.fedex.rg.servises.PlaylistUpdateService;
import org.fedex.rg.utils.Log;

public class RadioRocksPlaylistUpdater implements PlaylistUpdateService {

	private static final String URL = "http://jboss.noisyteam.org:8080/playlistgrabber-1.0-SNAPSHOT/playlist";

	@Override
	public List<Song> updatePlaylist() throws IOException {
		InputStream inputStream = getInputStreamFromUrl(URL);
		StringBuilder stringFromStream = inputStreamToString(inputStream);
		return parseString(stringFromStream);
	}

	private InputStream getInputStreamFromUrl(String url) {
		InputStream content = null;
		try {
			HttpClient httpclient = new DefaultHttpClient();
			HttpResponse response = httpclient.execute(new HttpGet(url));
			content = response.getEntity().getContent();
		} catch (Exception e) {
			Log.e(e.getMessage());
		}
		return content;
	}

	private StringBuilder inputStreamToString(InputStream is)
			throws IOException {
		String line = "";
		StringBuilder total = new StringBuilder();

		// Wrap a BufferedReader around the InputStream
		BufferedReader rd = new BufferedReader(new InputStreamReader(is));

		// Read response until the end
		while ((line = rd.readLine()) != null) {
			total.append(line);
		}

		// Return full string
		return total;
	}

	private List<Song> parseString(StringBuilder inputString) {
		List<Song> songs = new ArrayList<Song>();

		// removes []
		inputString.deleteCharAt(0);
		inputString.deleteCharAt(inputString.length() - 1);

		String[] splitedStrings = inputString.toString().replace('"', ' ')
				.split(",");
		for (int i = 0; i < splitedStrings.length; i++) {
			String[] titleArtist = splitedStrings[i].split("-");
			if (titleArtist.length == 2) {
				Song song = new Song(titleArtist[1].trim(),
						titleArtist[0].trim());
				songs.add(song);
			} else if (titleArtist.length == 1) {
				Song song = new Song(titleArtist[0].trim(), "");
				songs.add(song);
			}
		}
		return songs;
	}

}
